'''
Created on Sep 21, 2010

@author: johan
'''

from wsgiref.simple_server import make_server
from pprint import pprint
import json
from scxml.pyscxml import StateMachine
from time import sleep
import logging

logger = logging.getLogger("pyscxml.tropo_server")

def request_handler(environ, start_response):
    if environ['REQUEST_METHOD'] == 'POST':
        try:
            request_body_size = int(environ['CONTENT_LENGTH'])
            request_body = environ['wsgi.input'].read(request_body_size)
        except (TypeError, ValueError):
            request_body = "0"

        response_body = get_response(environ["PATH_INFO"], json.loads(request_body))
#        print "request"
#        pprint(json.loads(request_body))
        response_body2 = '''\
        {
    "tropo": [
        {
            "ask": {
                "say": [
                    {
                        "value": "Please say a number" 
                    }
                ],
                "required": true,
                "name": "foo",
                "choices": {
                    "value": "[DIGITS]" 
                } 
            } 
        },
        {
            "ask": {
                "say": [
                    {
                        "value": "Please say your account number" 
                    }
                ],
                "required": true,
                "name": "foo",
                "choices": {
                    "value": "[DIGITS]" 
                } 
            } 
        },
        {
            "on": {
                "next": "/send",
                "event": "continue" 
            } 
        } 
    ]
}'''

        status = '200 OK'
        headers = [('Content-type', 'text/plain')]
        start_response(status, headers)
        return [response_body]




sm_mapping = {}

def get_response(path, json_request):
    if path == "/init":

        print "init"
        sm = StateMachine(xml)
        sm_mapping[json_request['session']['callId']] = sm
        sm.start()
        
        
        while not sm.datamodel.has_key("_tropo"):
            sleep(0.5)
        
        print "sending", sm.datamodel["_tropo"].RenderJson()
        return sm.datamodel.pop("_tropo").RenderJson()
    
    elif path == "/send":
        
        sm = sm_mapping[json_request['result']['callId']]
        if not sm:
            print "error: sm undefined"
        
        print "request"
        pprint(json_request)
        
        if json_request["result"].get("actions"):
            if json_request["result"]["actions"].get("disposition") == "TIMEOUT":
                event = "tropo.timeout"
            elif json_request["result"]["actions"].get("disposition") == "NOMATCH":
                event = "tropo.nomatch"
            else:
                event = "tropo.answer.ask"
            
        elif json_request["result"].get("error"):
            event = "tropo.error"
        else:
#            name = "." + str(json_request["result"]["actions"]["name"] if str(json_request["result"]["actions"].get("name")
            event = "tropo.answer.say" 
            
        
        sm.send(event, data=json_request)
        
        while not sm.datamodel.has_key("_tropo"):
            sleep(0.5)
        print "sending", sm.datamodel["_tropo"].RenderJson()
        return sm.datamodel.pop("_tropo").RenderJson() 
        
        


def start_server(host, port, scxml_doc):
    """Start the server."""
    print "starting tropo server"
    global xml
    xml = scxml_doc
    httpd = make_server(host, port, request_handler)
    httpd.serve_forever()

if __name__ == "__main__":
    start_server("10.0.1.13", 8081, open("../../resources/tropo_colors.xml").read())

